package client;

import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

import javax.swing.JOptionPane;
import javax.swing.plaf.metal.MetalIconFactory;

import util.PointList;

public class Main {

	private static GUI gui;
	private static GuiListener gl;
	private static PointList pl;
	private static ReceiveThreadClient rec;
	private static String host;
	private static String p = "30001";

	public static void main(String[] args) {

		init();
		int port = 0;
		if (p == null || host == null) {
			System.exit(1);
		}
		if (p.equals("")) {
			port = 30001;
		} else {

			port = Integer.parseInt(p);
		}
		InetAddress ia = null;
		if (host == "" || host == null) {
			host = "localhost";
		}
		try {
			ia = InetAddress.getByName(host);
		} catch (UnknownHostException e1) {
			JOptionPane.showMessageDialog(null, "Invalid IP");
			e1.printStackTrace();
		}

		Socket socket = null;
		try {
			socket = new Socket(ia, port);
		} catch (IOException e) {
			e.printStackTrace();
			System.exit(1);
		}

		pl = new PointList();
		gl = new GuiListener(pl, socket);
		gui = new GUI(gl);
		gui.setVisible(true);
		rec = new ReceiveThreadClient(socket, gl);
		rec.start();
	}

	private static void init() {
		host = (String) JOptionPane.showInputDialog(GUI.sketchArea,
				"Enter IP-address of server", "IP",
				JOptionPane.QUESTION_MESSAGE, MetalIconFactory
						.getTreeComputerIcon(), null, "");
		p = (String) JOptionPane.showInputDialog(GUI.sketchArea,
				"Enter port of server", "Port", JOptionPane.QUESTION_MESSAGE,
				MetalIconFactory.getTreeComputerIcon(), null, "");

	}

}
